<template>
  <div>
    <!-- 导航栏区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand" width="50%">
          <template v-slot="scope">
            <!-- 一级权限 -->
            <el-row v-for="(obj,ind) in scope.row.children" :key="ind"
              :class="['bgbottom',ind===0?'bgtop':'','vcenter','bgleft']">
              <el-col :span="5">
                <el-tag @close="delRights(scope.row,obj.id)" closable>{{obj.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row v-for="(item,index) in obj.children" :key="index"
                  :class="[index===0?'':'bgtop','vcenter','bgleft']">
                  <el-col :span="6">
                    <el-tag type="success" @close="delRights(scope.row,item.id)" closable>{{item.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18" class="bgright">
                    <el-tag type="warning" v-for="(obj1,it) in item.children" :key="it"
                      @close="delRights(scope.row,obj1.id)" closable>{{obj1.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#" width="50%">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <!-- 编辑按钮 -->
            <el-button type="primary" class="el-icon-edit" size="mini" @click="showEditDialog(row.id)">
              编辑
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" class="el-icon-delete" size="mini" @click="delRoles(row.id)"> 删除</el-button>
            <!-- 分配角色 -->
            <el-button type="warning" class="el-icon-s-tools" size="mini" @click="showDialogVisible(row)"> 权限分配
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限提示框 -->
    <el-dialog title="分配权限" :visible.sync="dialogVisible" @close="dialogVisibleClosed" width="50%">
      <!-- 树形控件 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" :default-expand-all="true"
        :default-checked-keys="defKeys" ref="treeRef">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 弹出添加信息 -->
    <el-dialog title="添加信息" :visible.sync="addDialogVisible" @close="resetaddForm" width="50%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName" class="is-required">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" class="is-required">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑会话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" @close="reseteditForm" width="50%">
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName" class="is-required">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" class="is-required">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      // 获取角色列表
      rolesList: [],
      dialogVisible: false,
      rightsList: [],  // 权限列表
      treeProps: {            // 树形控件的属性绑定
        children: 'children',
        label: 'authName'
      },
      defKeys: [],   // 默认选中节点的id值
      roleId: '',      // 当前即将被分配的id
      addDialogVisible: false,  // 控制添加信息会话框
      // 添加表单验证数据
      addForm: {
        roleId: '',
        roleName: "",
        roleDesc: '',
      },
      addFormRules: {
        roleName: [
          { require: true, message: '请输入角色名称', trigger: 'blur' },          // trigger自动触发为鼠标事件
          {
            min: 3,
            max: 10,
            message: '角色名称长度为3到10个字符',
            trigger: 'blur'
          },
        ],
        roleDesc: [
          { require: true, message: '请输入角色描述', trigger: 'blur' },          // trigger自动触发为鼠标事件
          {
            min: 3,
            max: 10,
            message: '角色描述长度为3到10个字符',
            trigger: 'blur'
          },
        ],
      },
      editDialogVisible: false,
      editForm: {},   //  修改用户信息
    }
  },
  methods: {
    // 删除
    async delRoles (id) {
      const confirmResult = await this.$confirm('此操作将永久删除角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (confirmResult !== "confirm") {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success(res.meta.msg)
      this.getRoles()
    },
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('查询用户数据失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    reseteditForm () {
      this.$refs.editFormRef.resetFields()
      this.showDialogVisible()
    },
    //编辑提交角色
    editRoleInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, {
          roleName: this.editForm.roleName,
          roleId: this.editForm.roleId,
          roleDesc: this.editForm.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败')
        }
        this.editDialogVisible = false
        this.getRoles()
        this.$message.success("修改角色成功")
      })
    },
    // 添加角色
    addRoles () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success(res.meta.msg)
        this.addDialogVisible = false
        this.getRoles()
      })
    },
    resetaddForm () {
      this.$refs.addFormRef.resetFields()
    },
    async allotRight () {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const strId = keys.join(',')
      // console.log(strId);
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: strId })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success(res.meta.msg)
      this.getRoles()
      this.dialogVisible = false
    },
    // 监听分配权限的关闭
    dialogVisibleClosed () {
      this.defKeys = []
    },
    // 通过递归获取三级权限   node为权限对象  arr为储存三级权限id的数组
    // getLeafKeys (node, arr) {
    //   // 如果当前数组不包含children属性则为三级权限
    //   if (!node.children) {
    //     return arr.push(node.id)
    //   }
    //   node.children.forEach(obj => this.getLeafKeys(obj, arr));
    // },
    async showDialogVisible (row) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightsList = res.data
      const arr = []
      console.log(row.children);
      row.children.forEach(item1 => {
        if (item1.children && item1.children.length > 0) {
          item1.children.forEach(item2 => {
            if (item2.children && item2.children.length > 0) {
              item2.children.forEach(item3 => {
                return arr.push(item3.id)
              })
            }
          })
        }
      })
      // function fn (obj) {
      //   if (obj.children && obj.children.length > 0) {
      //     obj.children.forEach(item => fn(item))
      //   } else {
      //     return arr.push(obj.id)
      //   }
      // }
      // fn(row)
      // console.log(arr);
      this.defKeys = arr
      this.roleId = row.id
      // 递归获取三级权限节点id
      // this.getLeafKeys(role, this.defKeys)
      this.dialogVisible = true
    },
    async delRights (role, id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (confirmResult !== "confirm") {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${id}`)
      if (res.meta.status !== 200) return this.$message.error('取消权限失败')
      this.$message.success(res.meta.msg)
      // 直接赋值  重新渲染加载数据无效  因为删除后后台数据又会返回新的角色数据
      role.children = res.data
      this.showDialogVisible()
    },
    async getRoles () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rolesList = res.data
      //   console.log(res.data);
    }

  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getRoles()
  },
  mounted () { }
}
</script>

<style lang='less' scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-tag {
  margin: 7px;
}
.bgtop {
  border-top: 1px solid #eee;
}
.bgbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
.bgleft {
  border-left: 1px solid #eee;
}
.bgright {
  border-right: solid 1px #eee;
}
</style>